
const jwt = require('jsonwebtoken');
const constant = require('../provider/constant')

module.exports = {
    jwt: async (ctx, next) => {
        const token = ctx.header.authorization || ctx.cookies.get(constant.jwt_cookie_name) // 获取jwt
        //console.log(token, ctx.header.authorization, ctx.cookies.get('Authorization'))
        let payload
        if (token) {
            payload = await jwt.decode(token, constant.jwt_scret)  // 解密，获取payload
            if (payload && payload.id) {
                ctx.token = payload;
            }
        }
        return next().catch(async (err) => {
            if (401 == err.status) {
                ctx.status = 401;
                await ctx.render('auth', {
                    status: 401
                })
            } else {
                throw err;
            }
        });
    }
}